let socket: WebSocket | null = null
const message: any = null
let callbackEvent: any = null
function initWebSocket(event, api) {
  let protocol = `wss://${window.location.hostname}/ddf-api` // 默认是线上的域名
  if (window.location.protocol === 'http:') {
    protocol = 'ws://192.168.3.145:7210' // 配置开发域名
  }
  const socketURL = `${protocol}${api}`
  socket = new WebSocket(socketURL)
  callbackEvent = event

  socket.addEventListener('open', () => {
    console.log('WebSocket连接已建立')
  })

  socket.addEventListener('message', (event) => {
    const message = event.data
    callbackEvent(JSON.parse(message))
    // console.log('收到消息：', message);
    // 处理收到的消息
  })

  socket.addEventListener('close', () => {
    console.log('WebSocket连接已关闭')
  })

  socket.addEventListener('error', (error) => {
    console.error('WebSocket错误：', error)
  })
}
//  处理收到的消息
function websocketonmessage() {
  return message
}
// 发送消息
function sendWebSocket(message: string) {
  if (socket && socket.readyState === WebSocket.OPEN) {
    socket.send(message)
  } else {
    console.error('WebSocket连接未打开')
  }
}
// 关闭 WebSocket 连接
function closeWebSocket() {
  if (socket) {
    socket.close()
  }
}

export { initWebSocket, sendWebSocket, closeWebSocket, websocketonmessage }
